<!-- from 7 5 2 7 1 8 9 2 0 -->
<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="4" :sm="24">
                <a-form-item :label="$t('reportQuery.warehouse')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    mode="multiple" :maxTagCount="1"
                    optionFilterProp="children"
                    showSearch style="width: 100%"
                    :placeholder="$t('reportQuery.pleaseSelectAWarehouse')"
                    v-model="depotSelected">
                    <a-select-option v-for="(depot,index) in depotList" :value="depot.id" :key="index">
                      {{ depot.depotName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="3" :sm="24">
                <a-form-item :label="$t('reportQuery.category')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select style="width:100%" :dropdownStyle="{maxHeight:'200px',overflow:'auto'}" allow-clear
                       :treeData="categoryTree" v-model="queryParam.categoryId" :placeholder="$t('reportQuery.pleaseCategory')">
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item :label="$t('reportQuery.productInformation')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :placeholder="$t('reportQuery.barcodeModel')" v-model="queryParam.materialParam"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="3" :sm="24">
                <a-form-item :label="$t('reportQuery.zeroInventory')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select v-model="queryParam.zeroStock">
                    <a-select-option value="0">{{$t('reportQuery.hide')}}</a-select-option>
                    <a-select-option value="1">{{$t('reportQuery.display')}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <span class="table-page-search-submitButtons  table-operator">
                  <a-button type="primary" @click="searchQuery">{{$t('reportQuery.query')}}</a-button>
            
            <a-popconfirm
              :title="$t('commodityManagement.saveStockTips')"
              :disabled="save_loading"
              @confirm="storageStock">
              <a-button type="danger" :loading="save_loading">{{$t('commodityManagement.saveCurrentInventory')}}</a-button>
              <span class="gap"></span>
            </a-popconfirm>  
            <a-popconfirm
              :title="$t('commodityManagement.countStockTips')"
              :disabled="count_loading"
              @confirm="countStock">
              <a-button type="danger" :loading="count_loading">{{$t('commodityManagement.countStock')}}</a-button>
              <span class="gap"></span>
            </a-popconfirm>
               
                 <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? $t('manuManagement.putAway') : $t('manuManagement.open') }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                  </a> 
                </span>
              </a-col>
              <a-col :span="24" v-if="toggleSearchStatus">
                <ColumnsSetting style="ma" @columnsChange="columnsChange" :columns="columns"></ColumnsSetting>
                <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="reportPrint" icon="printer">{{$t('reportQuery.print')}}</a-button>
                  <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="generatePrintData" icon="printer">{{$t('inPrint.other') + $t('reportQuery.print')}}</a-button>
                  <a-button v-if="btnEnableList.indexOf(3) > -1" :loading="downLoading" style="margin-left: 8px" @click="exportExcel" icon="download">{{$t('reportQuery.export')}}</a-button>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item>
                  <span>{{$t('reportQuery.totalInventory')}}：{{currentStock}}，{{$t('reportQuery.totalInventoryAmount')}}：{{currentStockPrice}}</span>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- table区域-begin -->
        <section ref="print" id="reportPrint">
          <a-table
            bordered
            ref="table"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="false"
            :scroll="scroll"
            :loading="loading"
            @change="handleTableChange">
              <span slot="action" slot-scope="text, record">
                <a @click="showMaterialInOutList(record)">{{record.id?$t('reportQuery.flow'):''}}</a>
              </span>
          </a-table>
          <a-row :gutter="24" style="margin-top: 8px;text-align:right;">
            <a-col :md="24" :sm="24">
              <a-pagination @change="paginationChange" @showSizeChange="paginationShowSizeChange"
                size="small"
                show-size-changer
                :showQuickJumper="true"
                :current="ipagination.current"
                :page-size="ipagination.pageSize"
                :page-size-options="ipagination.pageSizeOptions"
                :total="ipagination.total"
                :show-total="(total, range) => $t('reportQuery.common') +`${total-Math.ceil(total/ipagination.pageSize)}`+ $t('reportQuery.strip')">
                <template slot="buildOptionText" slot-scope="props">
                  <span>{{ props.value-1 }}{{$t('reportQuery.strip')}}/{{$t('reportQuery.page')}}</span>
                </template>
              </a-pagination>
            </a-col>
          </a-row>
        </section>
        <!-- table区域-end -->
        <material-in-out-list ref="materialInOutList" @ok="modalFormOk"></material-in-out-list>
      </a-card>
    </a-col>
    <saleOutRepotModual ref="saleOutRepotModual" :list="dataSource" :columns="columns" :queryParam="queryParam"></saleOutRepotModual>
  </a-row>
</template>
<script>
  import MaterialInOutList from './modules/MaterialInOutList'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { getAction,postAction } from '@/api/manage'
  import {queryMaterialCategoryTreeList,showPurchase} from '@/api/api'
  import { getMpListShort, openDownloadDialog, sheet2blob} from "@/utils/util"
  import JEllipsis from '@/components/jeecg/JEllipsis'
  import moment from 'moment'
  import Vue from 'vue'
  import saleOutRepotModual from './modules/saleOutRepotModual';
  export default {
    name: "MaterialStock",
    mixins:[JeecgListMixin],
    components: {
      MaterialInOutList,
      JEllipsis,
      saleOutRepotModual
    },
    data () {
      return {
        labelCol: {
          span: 5
        },
        wrapperCol: {
          span: 18,
          offset: 1
        },
        // 查询条件
        queryParam: {
          categoryId:'',
          materialParam:'',
          zeroStock: '0',
          mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
        },
        ipagination:{
          pageSize: 11,
          pageSizeOptions: ['11', '21', '31', '101', '201']
        },
        count_loading:false,
        save_loading:false,
        depotSelected:[],
        depotList: [],
        categoryTree:[],
        currentStock: '',
        currentStockPrice: '',
        downLoading:false,//导出按钮loading
        // 表头
        columns: [
          {
            title: this.$t('defaultTranslate.lineNumber'), dataIndex: 'rowIndex', width:40, align:"center",
            customRender:function (t,r,index) {
              return (t !== '合计') ? (parseInt(index) + 1) : t
            }
          },
          {title:this.$t('reportQuery.barcode'), dataIndex: 'mBarCode', width: 50},
          {title:this.$t('reportQuery.name'), dataIndex: 'name', width: 140, ellipsis:true},
          {title:this.$t('reportQuery.specification'), dataIndex: 'standard', width: 120, ellipsis:true},
          {title:this.$t('reportQuery.model'), dataIndex: 'model', width: 80, ellipsis:true},
          {title:this.$t('reportQuery.color'), dataIndex: 'color', width: 80, ellipsis:true},
          {title:this.$t('reportQuery.category'), dataIndex: 'categoryName', width: 80, ellipsis:true},
          {title:this.$t('reportQuery.unit'), dataIndex: 'unitName', width: 60, ellipsis:true},
          {title:this.$t('commodityManagement.purchasePrice'), dataIndex: 'purchaseDecimal', sorter: (a, b) => a.purchaseDecimal - b.purchaseDecimal, width: 60},
          {title:this.$t('commodityManagement.retailPrice'), dataIndex: 'commodityDecimal', sorter: (a, b) => a.purchaseDecimal - b.purchaseDecimal, width: 60},
          {title:this.$t('commodityManagement.SellingPrice'), dataIndex: 'wholesaleDecimal', sorter: (a, b) => a.purchaseDecimal - b.purchaseDecimal, width: 60},
          {title:this.$t('reportQuery.initialInventory'), dataIndex: 'initialStock', sorter: (a, b) => a.initialStock - b.initialStock, width: 60},
          {title:this.$t('reportQuery.inventory'), dataIndex: 'currentStock', sorter: (a, b) => a.currentStock - b.currentStock, width: 60},
          {title:this.$t('reportQuery.inventoryAmount'), dataIndex: 'currentStockPrice', sorter: (a, b) => a.currentStockPrice - b.currentStockPrice, width: 80},
          {title:this.$t('reportQuery.inventoryFlow'), dataIndex: 'action', align:"center", width: 100,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/material/getListWithStock"
        }
      }
    },
    created() {
      this.initColumnsSetting()
      this.getDepotData()
      this.loadTreeData()

    },
    methods: {
      moment,
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        if(this.depotSelected && this.depotSelected.length>0) {
          param.depotIds = this.depotSelected.join()
        }
        param.field = this.getQueryField();
        param.currentPage = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize-1;
        return param;
      },
      getDepotData() {
        getAction('/depot/findDepotByCurrentUser').then((res)=>{
          if(res.code === 200){
            this.depotList = res.data;
          }else{
            this.$message.info(res.data);
          }
        })
      },
      loadTreeData(){
        let that = this;
        let params = {};
        params.id='';
        queryMaterialCategoryTreeList(params).then((res)=>{
          if(res){
            that.categoryTree = [];
            for (let i = 0; i < res.length; i++) {
              let temp = res[i];
              that.categoryTree.push(temp);
            }
          }
        })
      },
      searchQuery() {
        this.loadData(1);
      },

      //加载初始化列
      initColumnsSetting() {
        showPurchase().then((res) => {
          const index = this.columns.findIndex(v=>v.dataIndex === 'purchaseDecimal')
          if (res == true) {
            if (index === -1) {
              this.columns.splice(10,0,{ dataIndex: 'purchaseDecimal', title: this.$t('commodityManagement.purchasePrice'),width: 80 })
            }
          }else{
            if(index > -1){
              this.columns.splice(index,1)
            }
          }
        })
        
      },
      loadData(arg) {
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        let params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.code===200) {
            this.dataSource = res.data.rows;
            this.ipagination.total = res.data.total;
            this.tableAddTotalRow(this.columns, this.dataSource)
            this.currentStock = res.data.currentStock;
            this.currentStockPrice = res.data.currentStockPrice;
          }
          if(res.code===510){
            this.$message.warning(res.data)
          }
          this.loading = false;
        })
      },
      showMaterialInOutList(record) {
        let depotIds = ''
        if(this.depotSelected && this.depotSelected.length>0) {
          depotIds = this.depotSelected.join()
        }
        this.$refs.materialInOutList.show(record, depotIds,this.btnEnableList);
        this.$refs.materialInOutList.title = this.$t('reportQuery.viewFlow');
        this.$refs.materialInOutList.disableSubmit = false;
      },
      /**
       * 保存当前库存
       */
      storageStock(){
        this.save_loading = true;
        postAction('/material/saveStockHistory',{}).then(res=>{
          console.log('res :>> ', res);
          this.save_loading = false
                if(res.code == 200){
                  this.loadData(1)
                }else{
                  this.$message.error(res.msg || res.data.message)
                }
          }).catch(e=>{
            console.log(e);
          })
      },
      /**
       * 重新计算库存
       */
      countStock(){
        this.count_loading = true;
        setTimeout(()=>{
          this.getCountTask()
        },5000);
        postAction('/person/saveStockPerson',{}).then(res=>{
          console.log('res :>> ', res);
          if(res.code == 200) {
            postAction('/material/batchUpdateStock',{}).then(result=>{
              if(result.code == 200){
                this.loadData(1)
              }else{
                this.message.error(result.msg)
              }
            })
          }else{
            this.message.error(res.msg || res.data.message)
          }
        })
      },
      /**
       * 获取库存计算任务状态
       * 
       */
      getCountTask(){
        let timmer = null;
        const func = ()=>getAction('/person/findInfo',{name:'saveStock'}).then(res=>{
          if(res.code == 200){
            if(res.data.person && res.data.person.type === '0'){
              // 保存中
            }else if(res.data.person && res.data.person.type === '1' || !res.data.person){
              
              this.count_loading = false;
              // 保存完成
              clearInterval(timmer)
            }
          }else{
            this.$message.error(res.data)
          }
        })
        timmer = setInterval(() => {
          func()
        }, 1000);
        
      },
      getAllStock(){
        return new Promise((resolve, reject) => {
          let param = this.getQueryParams()
          param.pageSize = this.ipagination.total
          param.currentPage = 1
          let dataSource = []
          getAction('/material/getListWithStock',param).then(res=>{
                if(res.code == 200){
                  resolve(res.data.rows)
                }else{
                  this.$message.error(res.msg)
                  reject()
                }
          }).catch(e=>{
            console.log(e);
          })
        })
      },
      rowClick(record, index) {
      return {
        on: {
          click: () => {
          },
          dblclick: () => {
            console.log('双击了我')
            this.myHandleDetail(record, this.$t('purchasingManagement.receiptStock'))
          },
        }
      }
    },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>